package com.zzl.ov_library.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzl.ov_library.dto.Result;
import com.zzl.ov_library.entity.Books;
import com.zzl.ov_library.entity.Recommendation;
import com.zzl.ov_library.entity.RecommendationVO;
import com.zzl.ov_library.service.BooksService;
import com.zzl.ov_library.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class RecommendationController {
    @Autowired
    private RecommendationService recommendationService;

    @Autowired
    private BooksService booksService;

    //增加推荐书籍
    @PostMapping("/recommendation/add")
    public Result addRecommendation(@RequestBody Recommendation recommendation) {
        //通过isbn和手机号判断是否已存在
        Recommendation one = recommendationService.getOne(Wrappers.lambdaQuery(Recommendation.class)
                .eq(Recommendation::getIsbn, recommendation.getIsbn())
                .eq(Recommendation::getPhone, recommendation.getPhone()));
        System.out.println("one:"+one);
        if (one != null) {
            return Result.fail().setMsg("您已推荐该书籍");
        }

        //通过isbn判断是否有该书籍
        Books book = booksService.getOne(Wrappers.lambdaQuery(Books.class).eq(Books::getIsbn, recommendation.getIsbn()));
        System.out.println("recomBook:"+book);
        if (book != null) {
            return Result.fail().setMsg("书房已有该书籍");
        }
        System.out.println("recommendation:"+recommendation);
        return recommendationService.save(recommendation) ? Result.ok().setMsg("推荐成功") : Result.fail().setMsg("推荐失败");
    }

    //查询推荐书籍列表，并按照推荐次数排序
    @PostMapping("/recommendation/list")
    public Result listRecommendation(@RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "20") Integer limit) {
        Page<RecommendationVO> list = recommendationService.listRecommendation(page,limit);
        return Result.ok().setData(list);
    }

}
